using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
public class CrazyFood : MonoBehaviour
{
    public GameObject tipToastObject;
    public GameObject tipsContainer;
    public GameObject loadingUI;
    public GameObject lobbyUI;
    public Text coinsText;

    public GameObject centerUI;
    public GameObject levelsPrefab;
    public Text countDownText;
    private UnityAction countdownFinishedListener;
    public Text propsTimeText;
    public Text propsRefreshText;
    public Text propsChangeText;
    public Text propsStyleText;
    public InfiniteBounce props1Bounce;
    public InfiniteBounce props2Bounce;
    public InfiniteBounce props3Bounce;
    public InfiniteBounce props4Bounce;
    private bool isPlayCDSound = false;
    public GameObject notification;
    public Image notificationImage;
    public Text notificationText;

    //限时挑战
    public GameObject bottomUI0;
    public GameObject bottomUI1;
    public Text teslaText;
    public GameObject limitedLobbyUI;
    public Transform dialogTransform;
    public Image ct1;
    public Image ct2;
    public Text ct1Count;
    public Text ct2Count;
    private int limitedLevel;
    public Image bot_ct1;
    public Image bot_ct2;
    public Text bot_ct1Count;
    public Text bot_ct2Count;
    public Transform lvBox;
    public GameObject lvItem;

    public TipBg tipBg;
    public Transform rigidContainer;
    public Text dropCountText;

    void Awake()
    {
        Tools.TipToastObject = tipToastObject;
        Tools.TipsContainer = tipsContainer;
        Data.rigidContainer = rigidContainer;
        //监听开始
        GlobalEventManager.OnEvent("GameStart", OnGameStart); //开始游戏
        GlobalEventManager.OnEvent("EnterLobby", OnEnterLobby); //进入大厅
        GlobalEventManager.OnEvent<float>("UpdateCoins", OnUpdateCoins); //更新金币
        GlobalEventManager.OnEvent("NextLevel", OnNextLevel); //下一关
        GlobalEventManager.OnEvent("UpdatePropsCount", OnUpdatePropsCount); //更新道具数量
        GlobalEventManager.OnEvent("RestartGame", OnRestartGame); //重新开始
        countdownFinishedListener = () =>
        {
            Debug.Log("倒计时结束！");
            PanelManager.Instance.OpenPanel<TimeUpPanel>();
        };
        CountdownManager.Instance.SetOnCountdownFinishedListener(countdownFinishedListener);
        GlobalEventManager.OnEvent("LimitedTimeMode", OnLimitedTimeMode); //开始限时挑战游戏
        GlobalEventManager.OnEvent<float>("UpdateTesla", OnUpdateTesla); //更新金币
        GlobalEventManager.OnEvent<int>("TypesOfElimination", OnTypesOfElimination); //限时模式消除的类型
        GlobalEventManager.OnEvent<JObject>("OrderNotification", OnOrderNotification); //正常模式订单通知
        GlobalEventManager.OnEvent<int>("OrderElimination", OnOrderElimination); //订单判断
        GlobalEventManager.OnEvent<int>("ShowTipBg", OnShowTipBg); //显示TipBg
        GlobalEventManager.OnEvent<int>("DropEvent", OnDropEvent); //落地
        //监听结束
    }

    void OnDestroy()
    {
        GlobalEventManager.OffEvent("GameStart", OnGameStart);//开始游戏
        GlobalEventManager.OffEvent("EnterLobby", OnEnterLobby);//进入大厅
        GlobalEventManager.OffEvent<float>("UpdateCoins", OnUpdateCoins); //更新金币
        GlobalEventManager.OffEvent("NextLevel", OnNextLevel);//下一关
        CountdownManager.Instance.RemoveOnCountdownFinishedListener(countdownFinishedListener);
        GlobalEventManager.OffEvent("UpdatePropsCount", OnUpdatePropsCount); //更新道具数量
        GlobalEventManager.OffEvent("RestartGame", OnRestartGame); //重新开始
        GlobalEventManager.OffEvent("LimitedTimeMode", OnLimitedTimeMode); //开始限时挑战游戏
        GlobalEventManager.OffEvent<float>("UpdateTesla", OnUpdateTesla); //更新金币
        GlobalEventManager.OffEvent<int>("TypesOfElimination", OnTypesOfElimination); //限时模式消除的类型
        GlobalEventManager.OffEvent<JObject>("OrderNotification", OnOrderNotification); //正常模式订单通知
        GlobalEventManager.OffEvent<int>("OrderElimination", OnOrderElimination); //订单判断
        GlobalEventManager.OffEvent<int>("ShowTipBg", OnShowTipBg); //显示TipBg
        GlobalEventManager.OffEvent<int>("DropEvent", OnDropEvent); //落地
    }

    void Start()
    {
        initUI();
        //更新coins
        float _coins = UserManager.Instance.GetUserInfo()["Coins"].ToObject<float>();
        OnUpdateCoins(_coins);
        //更新tesla
        float _tesla = UserManager.Instance.GetUserInfo()["Tesla"].ToObject<float>();
        OnUpdateTesla(_tesla);
    }

    void Update()
    {
        // 更新倒计时显示
        if (CountdownManager.Instance.IsRunning)
        {
            countDownText.text = CountdownManager.Instance.GetFormattedTime();
            //如果countDownText.text小于12秒，则播放倒计时音效
            if (CountdownManager.Instance.CurrentTime < 12)
            {
                if (!isPlayCDSound)
                {
                    isPlayCDSound = true;
                    AudioManager.Instance.PlaySoundEffect("sounds_timer");
                }
                // Debug.Log(CountdownManager.Instance.CurrentTime.ToString());
            }
        }
        else
        {
            isPlayCDSound = false;
        }
    }

    private void OnOrderNotification(JObject data)
    {
        Debug.Log("订单通知" + JsonConvert.SerializeObject(data));
        ShowNotification(data);
    }
    private void initUI()
    {
        lobbyUI.SetActive(false);
        loadingUI.SetActive(true);
        limitedLobbyUI.SetActive(false);
        bottomUI0.SetActive(false);
        bottomUI1.SetActive(false);
        countDownText.text = CountdownManager.Instance.GetFormattedTime();
    }

    private void OnNextLevel()
    {
        Debug.Log("下一关");
        GenerateLevels();
        if (Data.mode == 1)
        {
            UpdateBotGoods();
        }
    }

    public void ShowNotification(JObject data)
    {
        Data.order = data;
        Debug.Log("订单通知" + JsonConvert.SerializeObject(data));
        notification.SetActive(true);
        Sprite[] sprites = ResManager.Instance.GetGoodsIcons();
        notificationImage.sprite = sprites[(int)data["Type"]];
        notificationText.text = "x" + data["Order"];

        RectTransform rectTransform = notification.GetComponent<RectTransform>();
        rectTransform.anchoredPosition = new Vector2(-725f, rectTransform.anchoredPosition.y);
        rectTransform.DOAnchorPosX(-470f, 0.2f).SetEase(Ease.OutQuad);
    }

    public void HideNotification()
    {
        // 执行滑出动画
        notification.GetComponent<RectTransform>().DOAnchorPosX(-725f, 0.2f).SetEase(Ease.InQuad)
            .OnComplete(() =>
            {

            });
    }

    private void OnOrderElimination(int type)
    {
        if (Data.order == null) return;
        if ((int)Data.order["Type"] == type)
        {
            UserManager.Instance.AddTesla((int)Data.order["Star"]);
            HideNotification();
            StartCoroutine(WaitFun());
        }
    }

    private IEnumerator WaitFun()
    {
        yield return new WaitForSeconds(20f);
        PanelManager.Instance.OpenPanel<OrderNotificationPanel>();
    }

    private void OnUpdateCoins(float coins)
    {
        Debug.Log("更新金币");
        float currtValue = 0;
        if (float.TryParse(coinsText.text, out float parsedValue))
        {
            currtValue = parsedValue;
        }
        DOTween.To(() => currtValue, x => currtValue = x, coins, 0.5f).OnUpdate(() =>
        {
            coinsText.text = currtValue.ToString("F2");
        });
    }

    private void OnUpdateTesla(float tesla = 0)
    {
        Debug.Log("更新Tesla");
        float currtValue = 0;
        if (float.TryParse(teslaText.text, out float parsedValue))
        {
            currtValue = parsedValue;
        }
        DOTween.To(() => currtValue, x => currtValue = x, tesla, 0.5f).OnUpdate(() =>
        {
            teslaText.text = currtValue.ToString("F2");
        });
    }

    private void OnGameStart()
    {
        Debug.Log("正常模式游戏");

        bottomUI0.SetActive(true);
        bottomUI1.SetActive(false);
        limitedLobbyUI.SetActive(false);
        notification.SetActive(true);
        //重置数据
        GoodsManager.Instance.ClearAllGoods();
        GenerateLevels();
        //弹出BoosterPanel
        PanelManager.Instance.OpenPanel<BoosterPanel>();
        //更新道具数量
        OnUpdatePropsCount();
    }

    private void OnShowTipBg(int type)
    {
        // 显示角色
        tipBg.transform.gameObject.SetActive(true);
        Transform jonny = tipBg.transform.Find("Jonny");

        if (type == 1)
        {
            jonny.Find("Zeus").gameObject.SetActive(true);
        }

        if (type == 0)
        {
            jonny.Find("Zeus").gameObject.SetActive(false);
        }

        float x = -Screen.width / 2 - jonny.GetComponent<RectTransform>().rect.width / 2;
        jonny.localPosition = new Vector3(x, 0, 0);
        CanvasGroup tcg = tipBg.transform.GetComponent<CanvasGroup>();
        tcg.alpha = 0;
        tipBg.SetData();

        tcg.DOFade(1f, 0.2f)
        .OnComplete(() =>
        {
            jonny.DOLocalMoveX(0, 0.3f).SetEase(Ease.OutQuad)
            .OnComplete(() =>
            {
                // 等待2秒
                StartCoroutine(WaitAndMoveOut(jonny, x));
            });
        });
    }

    private IEnumerator WaitAndMoveOut(Transform jonny, float x)
    {
        // 等待2秒
        yield return new WaitForSeconds(1f);
        // 执行离开动画
        jonny.DOLocalMoveX(-x, 0.3f).SetEase(Ease.OutQuad)
       .OnComplete(() =>
        {
            tipBg.transform.gameObject.SetActive(false);

            int guide = PlayerPrefs.GetInt("Guide", 0);
            int _level = (int)UserManager.Instance.GetUserInfo()["CurrentLv"];
            if (guide == 0 && _level == 1)
            {
                // GuideManager.Instance.ShowGuide();
            }
        });
    }



    private void OnLimitedTimeModeGameStart()
    {
        Debug.Log("限时挑战游戏");
        //重置数据
        GoodsManager.Instance.ClearAllGoods();
        GenerateLevels();
    }

    public async void OnStartCompetitionClick()
    {
        await FadeManager.Instance.FadeIn();
        limitedLobbyUI.SetActive(false);
        OnLimitedTimeModeGameStart();
        await FadeManager.Instance.FadeOut();
        OnShowTipBg(0);
    }

    private void OnTypesOfElimination(int type)
    {
        Debug.Log("限时模式消除的类型" + type);
        int bcount1 = int.Parse(bot_ct1Count.text);
        int bcount2 = int.Parse(bot_ct2Count.text);

        if (type == (int)Data.tt[0])
        {
            bcount1 -= 3;
            if (bcount1 <= 0)
            {
                bcount1 = 0;
            }
        }
        else if (type == (int)Data.tt[1])
        {
            bcount2 -= 3;
            if (bcount2 <= 0)
            {
                bcount2 = 0;
            }
        }

        int ct1Value = 0;
        if (int.TryParse(bot_ct1Count.text, out int parsedValue1))
        {
            ct1Value = parsedValue1;
        }
        DOTween.To(() => ct1Value, x => ct1Value = x, bcount1, 0.2f).OnUpdate(() =>
        {
            bot_ct1Count.text = $"{ct1Value}";
        });

        int ct2Value = 0;
        if (int.TryParse(bot_ct2Count.text, out int parsedValue2))
        {
            ct2Value = parsedValue2;
        }
        DOTween.To(() => ct2Value, x => ct2Value = x, bcount2, 0.2f).OnUpdate(() =>
        {
            bot_ct2Count.text = $"{ct2Value}";
        });

        if (bcount1 == 0 && bcount2 == 0)
        {
            //限时模式通关
            Debug.Log("限时模式通关");
            CountdownManager.Instance.Stop(); // 停止倒计时
            PanelManager.Instance.OpenPanel<PassPanel>();
        }
        else
        {
            List<Goods> allGoods = GoodsManager.Instance.GetAllGoods();
            Debug.Log("所有商品" + allGoods.Count);
            if (allGoods.Count <= 0)
            {
                // 游戏通关
                Debug.Log("游戏通关");
                CountdownManager.Instance.Stop(); // 停止倒计时
                PanelManager.Instance.OpenPanel<PassPanel>();
            }
            else
            {
                //判断是否空间不足
                var status = GameManager.Instance.GetGameStatus();
                if (status.isGameLose)
                {
                    Tools.Log("判断游戏状态", "前排没有位置了");
                    PanelManager.Instance.OpenPanel<RevivePanel>();
                }
                else if (status.isGameShuffle)
                {
                    Tools.Log("判断游戏状态", "没有可消除的");
                    PanelManager.Instance.OpenPanel<NoticePanel>();
                }
            }
        }
    }

    private void OnLimitedTimeMode()
    {
        Debug.Log("限时挑战大厅");
        bottomUI0.SetActive(false);
        bottomUI1.SetActive(true);
        limitedLobbyUI.SetActive(true);
        notification.SetActive(false);

        ShowDialog();
        UpdateBotGoods();
    }

    private void UpdateBotGoods()
    {
        //更新collection target
        JArray levels = (JArray)Data.gameConfig["levels_limited"];
        int _level = (int)UserManager.Instance.GetUserInfo()["LimitedLv"];
        limitedLevel = Mathf.Min(_level, levels.Count);

        JObject ct = (JObject)levels[limitedLevel - 1]["collection_target"];
        Data.tt = (JArray)ct["target_type"];
        Data.tc = (JArray)ct["target_count"];

        Sprite[] sprites = ResManager.Instance.GetGoodsIcons();

        ct1.sprite = sprites[(int)Data.tt[0]];
        ct2.sprite = sprites[(int)Data.tt[1]];

        ct1Count.text = $"x{(int)Data.tc[0]}";
        ct2Count.text = $"x{(int)Data.tc[1]}";

        bot_ct1.sprite = sprites[(int)Data.tt[0]];
        bot_ct2.sprite = sprites[(int)Data.tt[1]];

        bot_ct1Count.text = $"{(int)Data.tc[0]}";
        bot_ct2Count.text = $"{(int)Data.tc[1]}";

        //移除lvBox下的所有子物体
        foreach (Transform child in lvBox)
        {
            Destroy(child.gameObject);
        }

        for (int i = _level - 1; i < levels.Count; i++)
        {
            GameObject prefab = Instantiate(lvItem);
            prefab.transform.SetParent(lvBox, false);
            prefab.GetComponent<LvItem>().SetData(i + 1);
        }
    }

    private void ShowDialog()
    {
        // 设置初始缩放为0
        dialogTransform.localScale = Vector3.zero;

        // 执行缩放动画
        dialogTransform.DOScale(Vector3.one, 0.3f)
            .SetDelay(0.2f)
            .SetEase(Ease.OutBack)
            .OnComplete(() =>
            {
                Debug.Log("对话框缩放动画完成");
            });
    }

    private void OnRestartGame()
    {
        Debug.Log("重新开始");
        GoodsManager.Instance.ClearAllGoods();
        GenerateLevels();
    }

    private void OnUpdatePropsCount()
    {
        int c1 = PropsManager.Instance.GetPropCount(PropsManager.PropType.Prop1);
        int c2 = PropsManager.Instance.GetPropCount(PropsManager.PropType.Prop2);
        int c3 = PropsManager.Instance.GetPropCount(PropsManager.PropType.Prop3);
        int c4 = PropsManager.Instance.GetPropCount(PropsManager.PropType.Prop4);

        propsTimeText.text = c1.ToString();
        propsRefreshText.text = c2.ToString();
        propsChangeText.text = c3.ToString();
        propsStyleText.text = c4.ToString();

        if (c1 > 0)
        {
            props1Bounce.StartBouncing();
        }
        else
        {
            props1Bounce.StopBouncing();
        }

        if (c2 > 0)
        {
            props2Bounce.StartBouncing();
        }
        else
        {
            props2Bounce.StopBouncing();
        }

        if (c3 > 0)
        {
            props3Bounce.StartBouncing();
        }
        else
        {
            props3Bounce.StopBouncing();
        }

        if (c4 > 0)
        {
            props4Bounce.StartBouncing();
        }
        else
        {
            props4Bounce.StopBouncing();
        }
    }

    private void GenerateLevels()
    {
        Data.IsGameOver = false;
        Debug.Log("生成关卡");
        //移除centerUI下的所有子物体
        foreach (Transform child in centerUI.transform)
        {
            Destroy(child.gameObject);
        }
        //生成关卡
        GameObject prefab = Instantiate(levelsPrefab);
        prefab.transform.SetParent(centerUI.transform, false);
        Data.levelsTransform = prefab.transform;

        Levels levels = prefab.GetComponent<Levels>();
        levels.InitLevels();
        //开始计时
        CountdownManager.Instance.StartCountdown(Data.countdownTime);
        if (Data.mode == 0)
        {
            JArray data = (JArray)Data.gameConfig["levels_normal"];
            int l = (int)UserManager.Instance.GetUserInfo()["CurrentLv"];
            int dc = (int)data[l - 1]["drop_count"];
            dropCountText.text = dc.ToString();
        }
    }

    private void OnDropEvent(int count)
    {
        Debug.Log("掉落事件");
        int dc = int.Parse(dropCountText.text);
        dc -= count;
        if (dc < 0) return;

        dropCountText.text = dc.ToString();
        if (dc <= 0 && !Data.IsGameOver)
        {
            dc = 0;
            Data.IsGameOver = true;
            CountdownManager.Instance.Stop(); // 停止倒计时
            PanelManager.Instance.OpenPanel<FailedPanel>();
            Cart.Instance.ClearAllGoods();
        }
    }

    private void OnEnterLobby()
    {
        // 播放音乐
        AudioManager.Instance.PlayMusic("bgmusic");
        Debug.Log("进入大厅");
        lobbyUI.SetActive(true);
    }

    public void OnSetClick()
    {
        // 打开面板
        PanelManager.Instance.OpenPanel<SettingPanel>();
    }

    public void OnPropsClick(int index)
    {
        Debug.Log("道具===>" + index);
        int count = 0;
        if (index == 0)
        {
            count = PropsManager.Instance.GetPropCount(PropsManager.PropType.Prop1);
        }
        else if (index == 1)
        {
            count = PropsManager.Instance.GetPropCount(PropsManager.PropType.Prop2);
        }
        else if (index == 2)
        {
            count = PropsManager.Instance.GetPropCount(PropsManager.PropType.Prop3);
        }
        else if (index == 3)
        {
            count = PropsManager.Instance.GetPropCount(PropsManager.PropType.Prop4);
        }

        if (count <= 0)
        {
            PanelManager.Instance.OpenPanel<PropsPanel>(index);
            return;
        }
        else
        {
            if (index == 0)
            {
                if (PropsManager.Instance.RemoveProp(PropsManager.PropType.Prop1, 1))
                {
                    Debug.Log("成功使用了一个 Prop1");
                    CountdownManager.Instance.AddTime(30);
                }
                else
                {
                    Debug.Log("Prop1 数量不足");
                }
            }
            else if (index == 1)
            {
                if (PropsManager.Instance.RemoveProp(PropsManager.PropType.Prop2, 1))
                {
                    Debug.Log("成功使用了一个 Prop2");
                    StartCoroutine(SkillManager.Instance.OnRefreshSkills());
                }
                else
                {
                    Debug.Log("Prop2 数量不足");
                }
            }
            else if (index == 2)
            {
                if (PropsManager.Instance.RemoveProp(PropsManager.PropType.Prop3, 1))
                {
                    Debug.Log("成功使用了一个 Prop3");
                    SkillManager.Instance.OnChangeSkills();
                }
                else
                {
                    Debug.Log("Prop3 数量不足");
                }
            }
            else if (index == 3)
            {
                if (PropsManager.Instance.RemoveProp(PropsManager.PropType.Prop4, 1))
                {
                    Debug.Log("成功使用了一个 Prop4");
                    SkillManager.Instance.OnChangeContainerStyleSkills();
                }
                else
                {
                    Debug.Log("Prop4 数量不足");
                }
            }

        }
        // SkillManager.Instance.OnRefreshSkills();
        // SkillManager.Instance.OnChangeSkills();
    }

    public async void OnBackClick()
    {
        Debug.Log("返回大厅");
        CountdownManager.Instance.Stop();
        countDownText.text = CountdownManager.Instance.GetFormattedTime();
        await FadeManager.Instance.FadeIn();
        //移除centerUI下的所有子物体
        foreach (Transform child in centerUI.transform)
        {
            Destroy(child.gameObject);
        }
        lobbyUI.SetActive(true);
        bottomUI0.SetActive(false);
        bottomUI1.SetActive(false);
        limitedLobbyUI.SetActive(false);

        Cart.Instance.ClearAllGoods();
        await FadeManager.Instance.FadeOut();
    }

}


